﻿using McMaster.Extensions.CommandLineUtils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SingleTileDown
{
    public class Program
    {
        static void Main(string[] args)
        {
            CommandLineApplication.Execute<Program>(args);
        }
        [Option(ShortName = "u")]
        public string UrlTemplate { get; set; }
        [Option(ShortName = "z")]
        public int Z { get; set; } = 3;
        [Option(ShortName = "x")]
        public int X { get; set; } = 8;
        [Option(ShortName = "y")]
        public int Y { get; set; } = 8;
        [Option(ShortName = "t")]
        public int Threads { get; set; } = 6;
        [Option(ShortName = "a")]
        public int Attempt { get; set; } = 4;
        public void OnExecute()
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var urlt = string.IsNullOrEmpty(UrlTemplate) ? "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{0}/{1}/{2}" : UrlTemplate;

            var url = string.Format(urlt, Z, Y, X);
            var filename = $"L{Z:D2}/R{Y.ToString("X8").ToLower()}/C{X.ToString("X8").ToLower()}.png";

            var fi = new FileInfo(filename);
            if (fi.Directory.Exists == false)
            {
                try
                {
                    fi.Directory.Create();
                }
                catch (Exception)
                {
                    throw;
                }
            }


            bool shouldDownload = false;
            if (fi.Exists == false)
            {
                shouldDownload = true;
            }
            else
            {
                if (fi.Length == 0)
                {
                    shouldDownload = true;
                }
            }
            if (shouldDownload)
            {
                Download(url, fi.FullName, Attempt);
            }



        }

        public static void Download(string url, string filename, int count = 2)
        {
            if (count > 0)
            {
                using (var wc = new WebClient())
                {
                    try
                    {
                        count--;
                        wc.DownloadFile(new Uri(url), filename);
                        Console.WriteLine($"Success [{url}] [{filename}] {count}");
                    }
                    catch (Exception)
                    {
                        Download(url, filename, count);
                    }
                }
            }
            else
            {
                Console.WriteLine($"Failed [{url}] [{filename}] ");
            }
        }
    }
}
